/**
 * widget-box drag and drop
 */
(function(){
    var $treeitem;
    var offX = 0, offY = 0;

    $("body").on("mousedown", ".tree .tree-folder,.tree-item", function(e){
        $treeitem = $(e.currentTarget);
        if($treeitem.length > 0){
            e.stopPropagation();
            $treeitem.addClass(".widget-box-moving");
            $treeitem.css({
                position    : "relative",
                zIndex      : 9999,
                top         : "0px",
                left        : "0px"
            });
            offX = e.clientX;
            offY = e.clientY;
        }
    });

    $("body").on("mousemove", function(e){
        if($treeitem){
            e.stopPropagation();
            $treeitem.css({
                top     : (e.clientY - offY) + "px",
                left    : (e.clientX - offX) + "px"
            });
        }
    });

    $("body").on("mouseup", function(e){
        if($treeitem){
            $treeitem.removeClass(".widget-box-moving");
            $treeitem.css({
                position: "static"
            });
            var dropFn = function(e){
                e.stopPropagation();
                var $dropitem = $(e.currentTarget);
                if($dropitem.hasClass("tree-folder")){
                    $dropitem.click();
                    $dropitem.find(".tree-folder-content").append($treeitem);
                }else if($dropitem.hasClass("tree-item")){
                    $dropitem.after($treeitem);
                }else{

                }
                $treeitem = null;
                $("body").off("mouseover", ".tree .tree-folder,.tree-item", dropFn);
            };
            $("body").on("mouseover", ".tree .tree-folder,.tree-item", dropFn);
            $("body").on("mousemove", ".tree .tree-folder,.tree-item", function(){
                $("body").off("mouseover", ".tree .tree-folder,.tree-item", dropFn);
            });
            $treeitem.hide();
            $treeitem.show();
        }
    });
})();
